if (undefined == gmailControler) {
    var gmailControler = (function() {
        var gPanel = $('#gmail_panel'),
            gmail_view = $('#gmail_view'),
            top_resize = $('#gmail_panel_top_resize'),
            msgListDom = gPanel.find("#gmail_min_view"),
            messageBody = gPanel.find("#gmail_max_view"),
            isZoomIn = false,
            loaderCenter = {imgColor: 'black', textCSS: {'color': 'black'}, boxCSS: {'opacity': 1, 'background-color': 'rgb(240, 240, 240)'}},
            loaderSendCenter = {imgColor: 'black',textCSS: {'color': 'black'}, boxCSS: {'opacity': 1, 'background-color':'rgb(240, 240, 240)'}, contCSS:{left:'512px'}},
            loaderTop = {imgColor: 'black', position:'up', text:'',textCSS: {'color': 'white'}, imgCSS: {'margin-top':'60px'}, boxCSS: {'opacity': 0, 'background-color': 'white'}, contCSS:{left:'128px'}},
            loaderBottom = {imgColor: 'black', position:'down', text:'',textCSS: {'color': 'black'}, imgCSS: {'margin-bottom':'-10px'}, boxCSS: {'opacity': 0, 'background-color': 'white'}, contCSS:{left:'128px'}},
            loader = new Workport.Loader(gPanel,{imgColor: 'black', textCSS: {'color': 'black'}}),
            nextPageToken = '',
            pageIndex = WPMoudleManager.getModule('gmail').index,
            listVM = '',
            msgVM = '',
            composeVM = '',
            wp_body = $('#wp_body'),
            authPanel = gPanel.find('.authorize'),
            syncing = false,
            getting_unread = false,
            gContacts = [],
            gmail_query = 'in:inbox', //'in:inbox category:primary'
            gmail_unread_query = 'label:inbox is:unread',//'label:inbox is:unread category:primary'
            without_Categories = ["CATEGORY_SOCIAL"],
            gmail_empty_message = 'Your Primary inbox is empty. Personal messages and messages not in other folders will be shown here.',
            cur_message = null,
            gmail_profile = undefined,
            g_profile = undefined,
            g_sender = undefined,
            timeoutID = undefined,
            _authorized_ = false,
            SignatureManager = undefined,
            Label_Group_Config = {
                inbox:{
                    labelId:'INBOX',
                    query:'in:inbox',
                    unread_query:'label:inbox is:unread',
                    nextPageToken:undefined,
                    data:undefined,
                    cur_message:undefined
                },
                drafts:{
                    labelId:'DRAFT',
                    query:'in:draft',
                    unread_query:'label:drafts is:unread',
                    nextPageToken:undefined,
                    data:undefined,
                    cur_message:undefined
                },
                send:{
                    labelId:'SENT',
                    query:'is:sent',
                    unread_query:'label:send is:unread',
                    nextPageToken:undefined,
                    data:undefined,
                    cur_message:undefined
                }
            },
            cur_label = Label_Group_Config['inbox'],
            _debug_ = true;

        var _log = function(msg) { if (_debug_) console.log(msg); };
        var _dir = function(obj) { if (_debug_) console.dir(obj); };

        function gmailResize() {
            var height = $(window).height(), bodyHeight = height - 60 - 20, viewHeight = bodyHeight - 37;
            gmail_view.height(height - 60);
            msgListDom.height(bodyHeight);
            messageBody.height(bodyHeight);
            gPanel.find('.gmail_layout_panel, .gmail_layout_panel_body').height(viewHeight);
            gPanel.find('.slimScrollDiv').height(viewHeight);
        };

        function autHandler(result) {
            if (!result || !result.error) {
                _authorized_ = true;1
                authPanel.hide();
                loader.show();

                Workport.Google.load('gmail', 'v1', function() {
                    $.getScript('lib/google/gmail.js', function() {
                        gmailControler.getProfile(function(result){
                            var mail_address = result.emailAddress.toLocaleLowerCase();
                            //get google all contacts
                            Workport.Google._getContacts(function(result){
                                _log(' contacts result :');_log(result);
                                var entry = result.feed.entry || [], link, photo = "", gd_email = '',tmp_all_email = '', address = '', title="";
                                _log('entry length : ' + entry.length);
                                for(var i= 0,l=entry.length;i<l;i++){
                                    photo = './imgs/40.png';
                                    gd_email = entry[i]['gd$email'];
                                    if(gd_email){
                                        title = entry[i].title['$t'];
                                        link = entry[i].link;
                                        for(var n=0, s=link.length;n<s;n++){
                                            if(link[n].type == 'image/*'){
                                                photo = link[n].href+"?access_token="+ Workport.Google.getAuthResult().access_token;
                                                break;
                                            }
                                        }
                                        for(var x = 0,ln = gd_email.length;x<ln;x++){
                                            address = gd_email[x].address.trim().toLocaleLowerCase();
                                            if(tmp_all_email.indexOf(address) == -1){
                                                gContacts.push({email:address, photo:photo, title:title, full_address:(title && title!=address) ? title+' <'+address+'>':address});
                                                if(mail_address == address){
                                                    g_sender = (title && title!=address) ? title+' <'+address+'>':address;
                                                }
                                                tmp_all_email += address;
                                            }
                                        }
                                    }
                                }
                                _log("show google contacts :: "); _log(gContacts);
                                _log("show google contacts length  :: ");_log(gContacts.length);

                                if(!g_sender){
                                    gapi.client.load('oauth2', 'v2', function() {
                                        var request = gapi.client.oauth2.userinfo.get();
                                        request.execute(function(result){
                                            _log('google user info :');_log(result);
                                            g_profile = result;
                                            if(!result.name){
                                                g_sender = mail_address;
                                            }
                                        });
                                    });
                                }
                            });
                        });

                        Workport.Google.Gmail.messages.listFull({
                            q: cur_label.query
                        }, function(data, nextPageToken) {
                            _log('Workport.Google.Gmail.messages.listFull result: ');_log(arguments);
                            gmailControler.getUnread(function(result) {
                                listVM.set('unreadNum', result.length || 0);
                            });
                            listVM = mailistFatory(data, nextPageToken);
                            msgListDom.html($('#gmail-list-content-template').html());
                            kendo.bind(msgListDom, listVM);
                            $('#gmail-list-header').show();

                            var isEmpty = gmailControler.isEmpty(data);
                            $('.gmail_layout_panel').slimScroll({
                                wheelStep: 20,
                                allowPageScroll: true,
                                width: '100%',
                                start: 'top',
                                touchScrollStep: 200,
                                disableFadeOut: true
                            }).bind('slimscroll', function(e, pos) {
                                if (pos == 'bottom') {
                                    gPanel.find('.more').trigger('click');
                                }
                                if (pos == 'top') {
                                    loader.setOptions(loaderTop); loader.show();
                                    gmailControler.sync();
                                }
                            });
                            gmailResize();
                            loader.hide();
                            timeoutID = setTimeout(gmailControler.sync, GMAIL_SYNC_INTERVAL);
                            // init then show first mail
                            gmailControler.showFirstMail();
                        });
                        setTimeout(gmailResize, 10);
                    });
                });
            }
        };

        return {
            init: function() {
                //this.minTmp();
                var btn_auth = gPanel.find('#gmail_login');
                btn_auth.off().click(function(e) {
                    Workport.Google.authorize(false, function(result) {
                        autHandler(result);
                    });
                });
                $('#gmail').html(gPanel);
                if(!window.gapi || !Workport.Google.isInited()){
                    msgListDom.html($('#gmail_error_template').html());
                    setTimeout(gmailControler.init, 30*1000);
                    return;
                }
                HomePage_Scrollable.registerZoomCallback(WPMoudleManager.getModule('gmail').index,
                    function() {
                        gmailControler.onZoomIn();
                        top_resize.toggleClass("main_common_f_13_13 main_common_m_13_13");
                        top_resize.attr("title",'Collapse');
                    },
                    function() {
                        gmailControler.onZoomOut();
                        top_resize.toggleClass("main_common_m_13_13 main_common_f_13_13");
                        top_resize.attr("title",'Expand');
                    }
                );
                top_resize.bind({
                    click: function(e) {
                        HomePage_Scrollable.zoom(WPMoudleManager.getModule('gmail').index);
                    }
                });
                loader.show();
                Workport.Google.checkAuth(function(result) {
                    loader.hide();
                    if (!result.error) {
                        autHandler(result);
                    } else {
                        authPanel.show();
                    }
                });
                $(window).resize(gmailControler.resize);
                gmailControler.resize();
            },
            reLoad:function(label){
                cur_label = label || cur_label;

            },
            withoutMe:function(mail_list){
                var arr = mail_list.split(','),ea = gmail_profile.emailAddress;
                for(var i = 0;i<arr.length;i++){
                    if(arr[i].indexOf(ea) > -1){
                        arr.splice(i,1);
                        i--;
                    }
                }
                return arr.join(', ');
            },
            gSender:function(){ return g_sender; },
            gProfile: function () { return g_profile; },
            gmailProfile:function(){ return gmail_profile; },
            getProfile:function(callback){
                Workport.Google.Gmail.getProfile({userId:'me'}, function(result){
                    gmail_profile = result;
                    _log('getProfile :');_log(gmail_profile);
                    if($.isFunction(callback)) callback(result);
                });
            },
            messageBody:messageBody,
            showFirstMail: function () {
                if(gmailControler._isEmpty_()){
                    gmailControler._composeMessage(null, 'create');
                }else{
                    var mailist = listVM.get('mailist');
                    if(mailist[0] && !listVM.get('cur_gmid')){
                        listVM.set('cur_gmid', mailist[0].id);
                        gmailControler._showMessage(mailist[0], function(result){});
                    }else{
                        if(cur_message)
                            gmailControler._showMessage(cur_message, function(result){});
                    }
                }
            },
            findMessage:function(msg_id){
                var mailist = listVM.get('mailist');
                for(var i = 0, l = mailist.length;i<l;i++){
                    if(mailist[i].id == msg_id)
                        return mailist[i];
                }
            },
            GoogleContacts:function(){ return gContacts; },
            imgOnError:function(target){ target.src = './imgs/40.png'; },
            minTmp: function() { },
            maxTmp: function() { },
            checkExistMessage: function (msg) {
                if(!msg) return false;
                var mlist = listVM.get('mailist'), id_str = '';
                for(var i = 0, l = mlist.length;i<l;i++){
                    id_str += mlist[i].id + ', ';
                }
                return id_str.indexOf(msg.id+'') > -1 ? true : false;
            },
            trash: function(idlist, callback) {
                var mailCount = idlist.length, conversation = mailCount > 1 ? 'conversations':'conversation';
                Workport.utils.alertMsg('Confirmation alert', 'Are you sure you want to move '+ mailCount +' '+conversation+ ' to Trash?', [{
                    name: 'Yes',
                    class: 'btn yes',
                    css: {},
                    action: function(e) {
                        loader.setOptions(loaderCenter);loader.show();
                        Workport.Google.Gmail.messages.trashMessages('me', idlist, function() {
                            loader.hide();
                            _log(idlist);_log(cur_message);
                            if(idlist.indexOf(listVM.get('cur_gmid')) > -1){
                                listVM.set('cur_gmid','');
                            }
                            if(gmailControler.checkExistMessage(cur_message)){
                                cur_message = undefined;
                                gmailControler.zoomOut();
                            }
                            Workport.utils.alertMsg('Confirmation alert', mailCount + ' '+ conversation + ' has been moved to Trash.', function() {});

                            var index = -1, mailist = listVM.get('mailist'), selist = listVM.get('selectist'), msgId = '';
                            for (var i = 0, l = mailist.length; i < l; i++) {
                                msgId = mailist[i].id;
                                index = idlist.indexOf(msgId);
                                if (index > -1) {
                                    idlist.splice(index, 1);
                                    mailist.splice(i, 1);
                                    index = selist.indexOf(msgId);
                                    if(index > -1){
                                        selist.splice(index,1);
                                    }
                                    i--;
                                }
                                if (idlist.length == 0) {
                                    break;
                                }
                            }
                            gmailControler.showFirstMail();
                            gmailControler.getUnread(function(result) {
                                listVM.set('unreadNum', result.length);
                            });

                            if(listVM.get('mailist').length == 0 && listVM.get('nextPageToken')){
                                gmailControler.getMore(listVM.get('nextPageToken'), function(result, nextPageToken) {
                                    var mlist = listVM.toJSON().mailist;
                                    mlist = mlist.concat(result);
                                    listVM.set('nextPageToken', nextPageToken);
                                    listVM.set('mailist', mlist);
                                    gmailControler.showFirstMail();
                                });
                            }else if(listVM.get('mailist').length == 0 && !listVM.get('nextPageToken')){
                                loader.setOptions(loaderCenter);
                                loader.show();
                                Workport.Google.Gmail.messages.listFull({
                                    q: gmail_query
                                }, function(result, nextPageToken) {
                                    for(var i = 0,l=result.length;i<l;i++){
                                        mailist.push(result[i]);
                                    }
                                    listVM.set('nextPageToken',nextPageToken);
                                    gmailControler.isEmpty();
                                    loader.hide();
                                    gmailControler.getUnread(function(result) {
                                        listVM.set('unreadNum', result.length);
                                    });
                                    gmailControler.showFirstMail();
                                });
                            }else{
                                gmailControler.showFirstMail();
                            }
                            if(callback) callback();
                        });
                    }
                }, {
                    name: 'No',
                    class: 'btn no',
                    css: {},
                    action: function(e) {
                        return;
                    }
                }]);
            },
            getUnread: function(callback) {
                if(getting_unread) return;
                getting_unread = true;
                Workport.Google.Gmail.messages.listMessages('me', cur_label.unread_query, function(result) {
                    _log('get unread:');
                    _log(result);
                    getting_unread = false;
                    callback((!result[0])?[]:result);
                });
            },
            setRead:function(idlist, callback){
                Workport.Google.Gmail.messages.modifyMessages('me', idlist, [], ['UNREAD'], function(){
                    var index = -1, mailist = listVM.get('mailist'), selist = idlist, msgId = '', star_index = -1;
                    for (var i = 0, l = mailist.length; i < l; i++) {
                        msgId = mailist[i].id;
                        index = idlist.indexOf(msgId), star_index = mailist[i].labelIds.indexOf('UNREAD');
                        if (index > -1 && star_index > -1) {
                            mailist[i].labelIds.splice(star_index,1);
                        }
                    }
                    listVM.set('mailist',mailist);
                    gmailControler.sync();
                    if($.isFunction(callback))callback();
                });
            },
            setUnread:function(idlist,callback){
                Workport.Google.Gmail.messages.modifyMessages('me', idlist, ['UNREAD'], [], function(){
                    var index = -1, mailist = listVM.get('mailist'), selist = idlist, msgId = '';
                    for (var i = 0, l = mailist.length; i < l; i++) {
                        msgId = mailist[i].id;
                        index = idlist.indexOf(msgId), star_index = mailist[i].labelIds.indexOf('UNREAD');
                        if (index > -1 && star_index == -1) {
                            mailist[i].labelIds.push('UNREAD');
                        }
                    }
                    listVM.set('mailist', mailist);
                    gmailControler.sync();
                    if($.isFunction(callback))callback();
                });
            },
            setStar:function(idlist, callback){
                Workport.Google.Gmail.messages.modifyMessages('me', idlist, ['STARRED'], [], function(result){
                    var index = -1, mailist = listVM.get('mailist'), selist = idlist, msgId = '', star_index = -1;
                    for (var i = 0, l = mailist.length; i < l; i++) {
                        msgId = mailist[i].id;
                        index = idlist.indexOf(msgId), star_index = mailist[i].labelIds.indexOf('STARRED');
                        if (index > -1 && star_index == -1) {
                            mailist[i].labelIds.push('STARRED');
                        }
                    }
                    if(cur_message && idlist.indexOf(cur_message.id)> -1){
                        gmailControler._showMessage(gmailControler.findMessage(cur_message.id));
                    }
                    listVM.set('mailist',mailist);
                    if($.isFunction(callback))callback();
                });
            },
            setUnStar:function(idlist, callback){
                Workport.Google.Gmail.messages.modifyMessages('me', idlist, [], ['STARRED'], function(){
                    var index = -1, mailist = listVM.get('mailist'), selist = idlist, msgId = '';
                    for (var i = 0, l = mailist.length; i < l; i++) {
                        msgId = mailist[i].id;
                        index = idlist.indexOf(msgId), star_index = mailist[i].labelIds.indexOf('STARRED');
                        if (index > -1 && star_index > -1) {
                            mailist[i].labelIds.splice(star_index,1);
                        }
                    }
                    if(cur_message && idlist.indexOf(cur_message.id) > -1){
                        gmailControler._showMessage(gmailControler.findMessage(cur_message.id));
                    }
                    listVM.set('mailist', mailist);
                    if($.isFunction(callback))callback();
                });
            },
            list: function(parm, callback) {
                loader.setOptions(loaderBottom); loader.show();
                Workport.Google.Gmail.messages.listFull(parm, function(data, nextPageToken) {
                    loader.hide();
                    if(gmailControler.isEmpty(data)){
                        return;
                    }
                    _log(data);
                    callback(data, nextPageToken);
                });
            },
            getMore: function(nextPageToken, callback) {
                if (nextPageToken) {
                    this.list({
                        pageToken: nextPageToken
                    }, function(data, nextPageToken) {
                        callback(data, nextPageToken);
                    });
                } else {
                    callback([], nextPageToken);
                }
            },
            sendReport:function(){
                Workport.Communication.sendReport('Gmail');
            },
            onZoomIn: function() { isZoomIn = true; this.sendReport(); },
            onZoomOut: function() { isZoomIn = false; },
            zoomIn: function() {
                if (!isZoomIn)
                    HomePage_Scrollable.zoomIn(pageIndex);
            },
            zoomOut: function() {
                if (isZoomIn)
                    HomePage_Scrollable.zoomOut(pageIndex);
            },
            getComposeVM: function () { return composeVM; },
            _composeMessage:function(msg, type){
                messageBody.html($('#gmail-edit-template').html());
                var vm = composeMessageFactory(msg, type);
                kendo.bind(messageBody, vm);
                composeVM = vm;
                getContent(msg);
                messageBody.find('.pinputs').kendoAutoComplete({
                    dataSource: gmailControler.GoogleContacts(),
                    dataTextField: "full_address",
                    filter: "contains",
                    placeholder: "",
                    dataBound:function(e){
                        var tg = $(e.target || e.sender.element), field = tg.data('msg_field'), val = tg.val();
                        var arr = val.split(',');
                        if(arr.length > MAX_MAIL_ACCOUNT){
                            val = arr.slice(0, MAX_MAIL_ACCOUNT).join(',');
                        }
                        tg.val(val);
                    },
                    separator: ", ",
                    template: '<div class="k-state-default" style="height: 40px;line-height: 40px; white-space:nowrap;">' +
                        '<i style="height: 40px;line-height: 40px;float: left; white-space:nowrap;">' +
                        '<img src=\"#:photo#\" onerror="gmailControler.imgOnError(this);" style="height: 100%;float:left;margin-right:10px;"/>#:full_address#</i></div>',
                });

                if(type && type != 'create'){
                    var editor = messageBody.find('#ta_gmail_compose').data('kendoEditor');
                    var html = $(editor.value()), style = '';
                    html.find('*').each(function(){
                        style =  $(this).attr('style');
                        if(style)
                            $(this).attr('style', style.replace(/font-face/ig,'font-family'));
                    });
                    $(editor.body).html(html);
                    editor.focus();
                    editor.paste('');
                }
                gmailResize();
            },
            composeMessage: function(msg, type) {
                _log('compose message ' + type);
                if(!_authorized_){
                    Workport.utils.alertMsg('Confirmation alert','Sign in to continue to Gmail.',function(){});
                    return;
                }
                this._composeMessage(msg, type);
                this.zoomIn();
            },
            _isEmpty_:function(result){ _log('call _isEmpty_'); if (listVM.get('mailist').length == 0){ return true; } return false; },
            isEmpty:function(result){
                _log('check Empty');
                if(result && result.error){
                    if(result.code == '401'){
                        Workport.Google.fastAuthorize(function(){
                            syncing = false;
                            gmailControler.sync();
                        });
                    }
                    gmail_view.find('#gmail_empty').show().find('div').html((result.error.message || result.error.errors.message || "") +'<br>'+
                    '<a href="javascript:gmailControler.sync();" title="Try Now" style="font-size: 14px; font-weight: bold; text-decoration: underline;">Try Now</a>');
                    return true;
                }
                if(listVM.get('mailist').length == 0 && !listVM.get('nextPageToken')){
                    gmail_view.find('#gmail_empty').show().find('div').text(gmail_empty_message);
                    return true;
                }
                gmail_view.find('#gmail_empty').hide();
                return false;
            },
            sync: function() {
                if(syncing) { return; }
                syncing = true;
                _log('... gmail sync ...');
                var mailist = listVM.get('mailist'), index, history, curMsg,
                    mailIds = [], addedMessages = [], deletedMessages = [], parseMessages = {};

                if(mailist.length === 0 && !listVM.get('nextPageToken')){
                    gmailControler.list({q:cur_label.query},function(result, nextPageToken){
                        gmailControler.getUnread(function(result) {
                            listVM.set('unreadNum', result.length);
                        });
                        listVM.set('mailist',result);
                        listVM.set('nextPageToken', nextPageToken);
                        listVM.set('startHistoryId', result[0]?result[0].historyId:undefined);
                        syncing = false;
                        loader.hide();
                        gmailControler.isEmpty();
                        gmailControler.showFirstMail();
                        timeoutID = setTimeout(gmailControler.sync, GMAIL_SYNC_INTERVAL);
                    });
                    return;
                }

                Workport.Google.Gmail.history.listHistory('me', listVM.get('startHistoryId'), function(startHistoryId, result) {
                    _log('StartHistoryId is : ' + startHistoryId);
                    _log('History result : '); _log(result);

                    if(gmailControler.isEmpty(result)){
                        syncing = false;
                        loader.hide();
                        timeoutID = setTimeout(gmailControler.sync, GMAIL_SYNC_INTERVAL);
                        return;
                    }
                    if(startHistoryId){
                        listVM.set('startHistoryId', startHistoryId);
                        cur_label.nextPageToken = startHistoryId;
                    }
                    if (result[0]) {
                        _log('syncing result[0]');
                        clearTimeout(timeoutID);
                        for (var i = 0, l = mailist.length; i < l; i++) {
                            mailIds.push(mailist[i].id);
                        }
                        // check unread num.
                        gmailControler.getUnread(function(result) { listVM.set('unreadNum', result.length); });
                        for (var c = 0, size = result.length; c < size; c++) {
                            if (result[c].messagesAdded) {
                                _log('history messagesAdded');
                                history = result[c].messagesAdded;
                                for (var i = 0; i < history.length; i++) {
                                    parseMessages[history[i].message.id] = {
                                        history: 'messagesAdded',
                                        message: history[i].message
                                    };
                                }
                            } else if (result[c].messagesDeleted) {
                                _log('history messagesDeleted');
                                history = result[c].messagesDeleted;
                                for (var i = 0; i < history.length; i++) {
                                    parseMessages[history[i].message.id] = {
                                        history: 'messagesDeleted',
                                        message: history[i].message
                                    };
                                }
                            } else if (result[c].labelsRemoved) {
                                _log('history labelsRemoved');
                                history = result[c].labelsRemoved;
                                for (var i = 0; i < history.length; i++) {
                                    parseMessages[history[i].message.id] = {
                                        history: 'labelsRemoved',
                                        message: history[i]
                                    }
                                }
                            } else if (result[c].labelsAdded) {
                                _log('history labelsAdded');
                                history = result[c].labelsAdded;
                                for (var i = 0; i < history.length; i++) {
                                    if(history[i].labelIds.indexOf(cur_label.labelId) > -1 && mailIds.indexOf(history[i].message.id) < 0){
                                        addedMessages.push(history[i].message);
                                    }else{
                                        parseMessages[history[i].message.id] = {
                                            history: 'labelsAdded',
                                            message: history[i]
                                        }
                                    }
                                }
                            }
                        }
                        for (var data in parseMessages) {
                            _log(parseMessages[data]);
                            var history = parseMessages[data].history,
                                message = parseMessages[data].message,
                                index = mailIds.indexOf(message.id || message.message.id);
                            switch (history) {
                                case 'messagesAdded':
                                    if (index < 0)
                                        addedMessages.push(message);
                                break;
                                case 'messagesDeleted':
                                    if (index < 0)
                                        deletedMessages.push(message);
                                break;
                                case 'labelsRemoved':
                                    if (message.labelIds.indexOf("INBOX") > -1) {
                                        deletedMessages.push(message.message);
                                        break;
                                    }
                                    if (index > -1) {
                                        for (var i = 0; i < message.labelIds.length; i++) {
                                            mailist[index].labelIds.splice(mailist[index].labelIds.indexOf(message.labelIds[i]), 1);
                                        }
                                    }
                                break;
                                case 'labelsAdded':
                                    if (index > -1) {
                                        for (var i = 0; i < message.labelIds.length; i++) {
                                            mailist[index].labelIds.push(message.labelIds[i]);
                                        }
                                    }
                                break;
                            }
                        }
                        _log('show deleted message : '); _log(deletedMessages);
                        _log('show new message : '); _log(addedMessages);
                        _log('show parse messages : '); _dir(parseMessages);
                        //delete mail
                        _log('befor mailst length is : ' + mailist.length);
                        mailist = overlap(mailist, deletedMessages);
                        _log('after mailst length is : ' + mailist.length);
                        // add new mail
                        if (addedMessages.length > 0) {
                            Workport.Google.Gmail.messages.getMessagesById('me', addedMessages, function(result) {
                                _log('add new mail insert list');
                                _log(result);
                                for (var i = result.length - 1; i >= 0; i--) {
                                    if (result[i].labelIds.indexOf(cur_label.labelId) > -1) {
                                        mailist.unshift(result[i]);
                                    }
                                }
                                listVM.set('mailist', mailist);
                                syncing = false;
                                loader.hide();
                                timeoutID = setTimeout(gmailControler.sync, GMAIL_SYNC_INTERVAL);
                                gmailControler.isEmpty();
                            });
                        } else {
                            listVM.set('mailist', mailist);
                            syncing = false;
                            loader.hide();
                            timeoutID = setTimeout(gmailControler.sync, GMAIL_SYNC_INTERVAL);
                            gmailControler.isEmpty();
                        }
                    } else {
                        syncing = false;
                        loader.hide();
                        timeoutID = setTimeout(gmailControler.sync, GMAIL_SYNC_INTERVAL);
                    }
                });
            },
            _showMessage:function(msg, callback){
                _log(msg);
                cur_message = msg;
                messageBody.html($('#messageTemplate').html());
                var vm = messageFactory(msg); msgVM = vm;
                kendo.bind(messageBody, vm);
                gmailResize();
                //  mark unread label
                if (msg.labelIds.indexOf('UNREAD') > -1) {
                    Workport.Google.Gmail.messages.modify('me', msg.id, [], ['UNREAD'], function(result) {
                        _log(result);
                        gmailControler.getUnread(function(data) {
                            listVM.set('unreadNum', data.length);
                        });
                        if (callback) callback(result);
                    });
                    return;
                }
                if (callback)
                    callback(null);
            },
            showMessage: function(msg, callback) { this.zoomIn(); this._showMessage(msg, callback); },
            saveInDrafts: function(msg, callback) {
                var self = this;
                loader.setOptions(loaderSendCenter);loader.show();
                gmailControler.messageBody.find('.pinput').each(function(){
                    if($(this).data('msg_field')) msg[$(this).data('msg_field')] = this.value;
                });
                msg.content = $('#ta_gmail_compose').data("kendoEditor").value();
                Workport.Google.Gmail.drafts.save(msg, function(result) {
                    loader.hide();
                    if(gmailControler.isEmpty(result)){
                        return;
                    }
                    if (callback) callback(result);
                    Workport.utils.alertMsg('Confirmation alert', 'Your message has been saved in Drafts.', function() {});
                    self.zoomOut();
                    gmailControler._showMessage(null,'create');
                });
            },
            send: function(msg, callback) {
                _log(msg);
                var self = this;

                function send() {
                    loader.setOptions(loaderSendCenter);loader.show();
                    Workport.Google.Gmail.messages.send(msg, function(resp) {
                        loader.hide();
                        if(resp.responseText){
                            var response = JSON.parse(resp.responseText);
                            Workport.utils.alertMsg('Error alert', response.error.message, function() {});
                            return;
                        }
                        gmailResize();
                        gmailControler.showFirstMail();
                        self.zoomOut();
                        Workport.utils.alertMsg('Confirmation alert', 'Your message has been sent.', function() {});
                    });
                }

                gmailControler.messageBody.find('.pinput').each(function(){
                    if($(this).data('msg_field')) msg[$(this).data('msg_field')] = this.value;
                });

                // check email to ,cc, bcc format
                if(msg.to.trim() == '' && msg.cc.trim() == '' && msg.bcc.trim() == ''){
                    Workport.utils.alertMsg('Error alert', 'Please specify at least one recipient.', function() {});
                    return;
                }
                if(!v_email_str_list(msg.to.trim())){
                    Workport.utils.alertMsg('Error alert', 'The email address "'+ Workport.utils.encodeHtml(msg.to.trim()) +'" is not recognized. Please fix it and try again.', function() {});
                    return;
                }
                if(!v_email_str_list(msg.cc.trim())){
                    Workport.utils.alertMsg('Error alert', 'The email address "'+ Workport.utils.encodeHtml(msg.cc.trim()) +'" is not recognized. Please fix it and try again.', function() {});
                    return;
                }
                if(!v_email_str_list(msg.bcc.trim())){
                    Workport.utils.alertMsg('Error alert', 'The email address "'+ Workport.utils.encodeHtml(msg.bcc.trim()) +'" is not recognized. Please fix it and try again.', function() {});
                    return;
                }

                msg.content = $('#ta_gmail_compose').data("kendoEditor").value();

                if (!msg.subject.trim() || !msg.content) {
                    Workport.utils.alertMsg('Confirmation alert', 'Are you sure you want to send this message without Subject or text in the body?', [{
                        name: 'Yes',
                        class: 'btn yes',
                        css: {},
                        action: function(e) {
                            send();
                        }
                    }, {
                        name: 'No',
                        class: 'btn no',
                        css: {},
                        action: function(e) {
                            return;
                        }
                    }]);
                } else
                    send();
            },
            resize: function() { gmailResize(); },
            parseLongFileName:function(filename){
                if(filename.length > 40){
                    return filename.substring(0, 15) +"..."+ filename.substring(filename.length - 10);
                }
                return filename;
            }
        };
    })();
}

function v_email(mail){
    if(mail[0] == '<' && mail[mail.length - 1] == '>'){
        mail = mail.substring(1, mail.length - 1);
    }
    _log('v_email : >' + mail+"<");
    var reg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
    return reg.test(mail.trim());
}

function v_email_str(email_str){
    _log('email_str : >' + email_str+"<");
    var arr = email_str.trim().split('<');
    if(arr.length > 1){
        return '<'+ arr[arr.length-1];
    }
    return v_email(email_str);
}

function v_email_str_list(mail_str){
    if(!mail_str) return true;
    var arr = mail_str.split(',');
    for(var i = 0, l=arr.length;i<l;i++){
        if(arr[i] != '' && !v_email_str(arr[i])){ return false; }
    }
    return true;
}

function overlap(arr, arr2) {
    var arr3 = new Array(), index = 0, i = 0, j = 0, has = false;
    for (i = 0; i < arr.length; i++) {
        has = false;
        for (j = 0; j < arr2.length; j++) {
            if (arr[i].id == arr2[j].id) {
                has = true;
                break;
            }
        }
        if (!has) {
            arr3[index++] = arr[i];
        }
    }
    return arr3;
}

function iFrameHeight() {
    var iframe = $('#gmail_panel').find("#iframepage"), contents = iframe.contents(), ifm = iframe[0];
    var subWeb = ifm.contentDocument;
    if (!subWeb.body) return;
    ifm.height = subWeb.body.scrollHeight + (Workport.getBrowser() == 'firefox' ? 20 : 0);
    $(subWeb).find('a:not([target=_blank])').prop('target', '_top');
    $(subWeb.body).css({'width':'470px','overflow':'auto'});
    ifm.width = subWeb.body.scrollWidth;
    if (!iframe.data('loaded') && Workport.getBrowser().indexOf('ie') > -1) {
        iframe.data('loaded',1);
        contents.find('body').html(iframe.attr('srcdoc'));
        setTimeout(iFrameHeight,100);
    }
}

function parseHeaders(headers) {
    var temp = {};
    if (!headers) return temp;
    for (var i = 0, l = headers.length; i < l; i++) {
        temp[headers[i].name] = headers[i].value;
    }
    return temp;
};

function getContent(message) {
    if(!message) return '';
    if (message.payload && message.payload.parts)
        return parseParts(message.payload.mimeType == "multipart/alternative" ? [message.payload.parts[1]] : message.payload.parts, message);
    if(message.payload)
        return decodePart(message.payload, message);
    return '';
}

function parseParts(parts, message) {
    var html = '', i = 0, l = parts.length;
    for (; i < l; i++) {
        if (parts[i].body && parts[i].body.size > 0) {
            html += decodePart(parts[i], message);
        }
        if (parts[i].parts) {
            html += parseParts(parts[i].parts, message);
        }
    }
    return html;
}

function decodePart(part, message) {
    var partheaders = parseHeaders(part.headers);
    switch (part.mimeType) {
        case '"multipart/alternative"':
            return parseParts(part.parts[1], message);
        break;
        case 'image/jpeg':
        case 'image/gif':
        case 'image/png':
            var link = 'https://mail.google.com/mail/u/0/?ui=2&ik='+message.threadId+'&view=att&th='+message.id+'&attid=0.'+(part.partId)+'&disp=safe;realattid='+part.body.attachmentId+';zw';
            if(partheaders["Content-ID"]){
                var cid = partheaders["X-Attachment-Id"];
                var img = $('#gmail_panel').find('iframe').contents().find('img[src="cid:' + cid + '"]');
                img.prop('src', link);
            }
        break;
        case 'text/html':
        //case 'text/plain':
            if(part.filename) return;
            var result = Workport.base64.utf8to16(atob(part.body.data.replace(/_/g, '/').replace(/-/g, '+')));
            return result.replace(/&nbsp;/ig," ");
        break;
    }
    return '';
};

function getHeaderVal(name, headers) {
    return headers[name] == 'undisclosed-recipients:;' ? '' : headers[name] || '';
}

function getAttchList(message) {
    var alist = [], headers;
    if (!message.payload || !message.payload.parts)
        return alist;
    for (var i = 0, l = message.payload.parts.length; i < l; i++) {
        if (message.payload.parts[i].filename.length > 0) {
            headers = parseHeaders(message.payload.parts[i].headers);
            alist.push({
                'filename': message.payload.parts[i].filename,
                'mimeType': message.payload.parts[i].mimeType,
                'attachmentId': message.payload.parts[i].body.attachmentId,
                'size': message.payload.parts[i].body.size,
                'fid': headers["X-Attachment-Id"],
                'partId':message.payload.parts[i].partId,
                'headers': headers,
                'link':'https://mail.google.com/mail/u/0/?ui=2&ik='+ message.threadId +'&view=att&th='+ message.id +'&attid=0.'+ message.payload.parts[i].partId +'&disp=safe&zw&saddbat='+ message.payload.parts[i].body.attachmentId
            });
        }
    }
    return alist;
}

function trans_Mail_list(mail_str){
    var arr = '', t_arr, mlist = '', mail = '', m = '';
    arr = mail_str.split(',');
    for(var i = 0, l=arr.length;i<l;i++){
        mail = arr[i].trim();
        t_arr = mail.split('<');
        if(t_arr.length == 2){
            m = t_arr[1].substring(0,t_arr[1].length - 1);
            mlist += (t_arr[0]+'&lt;<a href="mailto:'+ m +'">' + m + '</a>&gt; ');
        }else{
            if(v_email(mail)){
                mlist += '&lt;<a href="mailto:'+ mail +'">' + mail + '</a>&gt; ';
            }else
                mlist += mail;
        }
    }
    return mlist;
}

function messageFactory(message) {
    var payloadHeaders = {};
    if (message.payload) { payloadHeaders = parseHeaders(message.payload.headers); }
    var attachments = getAttchList(message);
    var vm = kendo.observable({
        message: message,
        Attachments: attachments,
        char:function(){
            var from = getHeaderVal('From', payloadHeaders).toLocaleUpperCase();
            var gContacts = gmailControler.GoogleContacts();
            for(var i=0,l=gContacts.length;i<l;i++){
                if(from.indexOf(gContacts[i].email.toLocaleUpperCase()) > -1){
                    return "<img class='char circle' data-from='"+ from +"' onerror=on_img_error(this) src='"+gContacts[i].photo+"'/>";
                    break;
                }
            }
            return (from[0] == '"' ? from[1] : from[0]);
        }(),
        subject: getHeaderVal('Subject', payloadHeaders) ? getHeaderVal('Subject', payloadHeaders) : "(no subject)",
        labelIds: function(){ return 'right UN_STAR ' + message.labelIds.join(' '); },
        displaylabelIds: function() { return '[ ' + this.get("labelIds").join(", ") + ' ]'; },
        snippet: function(){this.get('message').snippet;},
        from: function(){
            var from = getHeaderVal('From', payloadHeaders), arr = from.split('<');
            if(arr.length > 1){
                this.set('from_mail','<'+arr[1]);
                return arr[0];
            }
            return from;
        },
        from_mail:'',
        to: getHeaderVal('To', payloadHeaders),
        cc: getHeaderVal('Cc', payloadHeaders),
        showCC:function(){ return getHeaderVal('Cc', payloadHeaders) ? 'block':'none'; }(),
        date: kendo.toString(new Date(getHeaderVal('Date', payloadHeaders)), 'ddd, MMM dd, yyyy at h:mm tt'),
        content: function() { return getContent(message); },
        iframe_load:function(){
            getContent(message);
            var iframe = $('#gmail_panel').find("#iframepage"), contents = iframe.contents(), ifm = iframe[0];
            var subWeb = ifm.contentDocument;
            if (!subWeb.body) return;
            ifm.height = subWeb.body.scrollHeight + (Workport.getBrowser() == 'firefox' ? 20 : 0);
            $(subWeb).find('a:not([target=_blank])').prop('target', '_top');
            $(subWeb.body).css({'width':'470px','overflow':'auto'});
            ifm.width = subWeb.body.scrollWidth;
            if (!iframe.data('loaded') && Workport.getBrowser().indexOf('ie') > -1) {
                iframe.data('loaded',1);
                contents.find('body').html(iframe.attr('srcdoc'));
                setTimeout(iFrameHeight,100);
            }
        },
        download: function(e) {
            var attach = this.get('Attachments')[$(e.target).data('aindex')];
            $(document.body).append('<a href="' + attach.link + '">' + attach.filename + '</a><br>');
        },
        reply: function() { gmailControler.composeMessage(message, 'reply'); },
        replyAll: function() { gmailControler.composeMessage(message, 'replyall'); },
        forward: function() { gmailControler.composeMessage(message, 'forward'); },
        trash: function() { gmailControler.trash([message.id]); },
        t_starred:function(){ return message.labelIds.indexOf('STARRED') > -1 ? '':'Star'; },
        onStar:function(e){ gmailControler[message.labelIds.indexOf('STARRED') > -1 ? 'setUnStar':'setStar']([message.id]); },
        onUnread:function(){ gmailControler.setUnread([message.id]); }
    });
    return vm;
}

function mailistFatory(gmailist, nextPageToken) {
    var curTarget = null;
    var vm = kendo.observable({
        mailist: gmailist.resultSizeEstimate == 0 ? [] : gmailist,
        nextPageToken: nextPageToken,
        unreadNum: 0,
        startHistoryId: gmailist[0] ? gmailist[0].historyId : undefined,
        cur_gmid:'',
        onSync: function() { gmailControler.sync(); },
        sort_by_date:function(){
            var list = this.get('mailist'),arr = [];
            if(list.length == 0) return;
            for(var i = 0,l = list.length;i<l;i++){
                arr.push(list[i]);
            }
            arr.sort(function(a,b){
                var ha = new Date(getHeaderVal('Date',parseHeaders(a.payload.headers))).getTime(), hb = new Date(getHeaderVal('Date',parseHeaders(b.payload.headers))).getTime();
                return hb - ha;
            });
            for(var i = 0,l = list.length;i<l;i++){
                list[i] = arr[i];
            }
        },
        primary: function() { return 'Primary&nbsp(' + this.get('unreadNum') + ')'; },
        onUnread:function(e){
            if (this.get('selectist').length > 0) {
                gmailControler.setUnread(this.get('selectist'));
            }
            return false;
        },
        onTrash: function(e) {
            if (this.get('selectist').length > 0) {
                gmailControler.trash(this.get('selectist'));
            }
            return false;
        },
        selectist: [],
        trashOpacity: function() { return this.get('selectist').length > 0 ? '1' : '.5'; },
        trashCursor: function() { return this.get('selectist').length > 0 ? 'pointer' : 'default'; },
        onCreate: function() { gmailControler.composeMessage(false, 'create'); return false; },
        onMore: function(e) {
            var self = this;
            gmailControler.getMore(this.get('nextPageToken'), function(result, nextPageToken) {
                var mlist = vm.toJSON().mailist;
                mlist = mlist.concat(result);
                vm.set('nextPageToken', nextPageToken);
                vm.set('mailist', mlist);
            });
        },
        onStar: function(e) {
            var star = $(e.target), s = this.get('selectist'), starData = s.indexOf(star.data('gmid')) > -1 ? s : [star.data('gmid')];
            gmailControler[star.hasClass('STARRED') ? 'setUnStar':'setStar'](starData);
        },
        onImportant: function(e) { /* to do...*/ },
        onOpen: function(e) {
            var slist = this.get('selectist');
            if (slist.length == 1) {
                window.open('https://mail.google.com/mail/u/0/?pli=1#inbox/' + slist[0]);
                return;
            }
            window.open('https://mail.google.com/');
            return false;
        },
        onShowMail: function(e) {
            var target = $(e.target), gmid = target.data('gmid'), mailist = this.get('mailist'), self = this, unreadIndex = -1;
            this.set('cur_gmid', gmid);
            for (var i = 0, l = mailist.length; i < l; i++) {
                if (mailist[i].id === gmid) {
                    unreadIndex = mailist[i].labelIds.indexOf('UNREAD');
                    gmailControler.showMessage(mailist[i], function(result) {
                        if (unreadIndex > -1) {
                            mailist[i].labelIds = result.labelIds;
                            self.set('mailist', mailist);
                        }
                    });
                    if (unreadIndex > -1) {
                        mailist[i].labelIds.splice(unreadIndex, 1);
                    }
                    break;
                }
            }
            return false;
        }
    });
    return vm;
}

/*type = create || reply ||  reply all || forward*/
function composeMessageFactory(message, type) {
    var msg = {},
        From  = gmailControler.gSender(),
        cc = '',
        bcc = '',
        to = '',
        content = '',
        msg_attachments = [],
        attaches = [],
        headers = undefined,
        subject = '',
        action = 'Compose',
        MAX_SIZE = 25 * 1024 * 1024,
        date_format = 'ddd, MMM dd, yyyy at h:mm tt',
        readySend = false;

    if((message && type == 'create') || !type){
        message = $.extend({subject: '', to: '', cc: '', bcc: '', content: ''}, message);
        to = message.to||''; cc = message.cc||''; bcc = message.bcc||''; content = message.content||''; subject = message.subject||'';
    }else if (message) {
        msg.historyId = message.historyId;
        msg.labelIds = message.labelIds;
        msg.hreadId = message.hreadId;
        headers = parseHeaders(message.payload.headers);
        content = getContent(message);

        var hr = "<br/><br/><hr style='width: 100%; height: 1px;' color='#b5c4df' size='1' align='left'><br/>",
            from = trans_Mail_list(getHeaderVal('From', headers)),
            wrote = '<p>On ' + kendo.toString(new Date(headers['Date']), date_format) + ', '+ from +' wrote:</p>';

        if(type == 'forward'){
            wrote = "<span>---------- Forwarded message ----------</span><br>"
                + "<span>From: </span><span>" + from + "</span></br>"
                + "<span>Date: </span><span>" + kendo.toString(new Date(headers['Date']), date_format) +"</span></br>"
                + "<span>Subject: </span><span>" + getHeaderVal('Subject', headers) + "</span></br>"
                + "<span>To: </span><span>" + trans_Mail_list(getHeaderVal('To', headers)) + "</span></br></br></br>";
        }
        content = hr + wrote + content;
        msg_attachments = getAttchList(message);
        var arr_att = '', link = '';
            style = 'text-decoration: none; float: left;color:black;font-size:12px; padding:5px; border: 1px solid lightgray; margin:5px; background-color: rgb(240, 240, 240);';
        for(var i = 0,l = msg_attachments.length;i<l;i++){
            if(msg_attachments[i].headers["Content-ID"]) {continue;}
            arr_att += '<a title="Download '+ msg_attachments[i].filename +'" downtype="wp" style="'+ style +'" href="'+ msg_attachments[i].link +'">'+
                       gmailControler.parseLongFileName(msg_attachments[i].filename) +'</a>';
        }
        content += '<br>'+arr_att;

        function parseSubject(subject, action){
            if(subject.toLocaleString().indexOf(action.toLocaleString()) != 0){
                return action+": "+subject;
            }
            return subject;
        }

        switch (type) {
            case 'reply': // Re:
                to = getHeaderVal('From', headers);
                subject = parseSubject(getHeaderVal('Subject', headers),'Re');
                action = 'Reply';
                msg['Message-Id'] = getHeaderVal("Message-Id", headers);
                msg['Reply-To'] = getHeaderVal("From",headers);
                msg['In-Reply-To'] = getHeaderVal('In-Reply-To', headers) || msg['Message-Id'];
                msg['References'] = getHeaderVal('References', headers) || msg['Message-Id'];
            break;
            case 'replyall': // Re:
                to = getHeaderVal('From', headers)+', '+gmailControler.withoutMe(getHeaderVal('To', headers));
                cc = gmailControler.withoutMe(getHeaderVal('Cc', headers));
                subject = parseSubject(getHeaderVal('Subject', headers),'Re');
                action = 'Reply All';
                msg['Message-Id'] = getHeaderVal("Message-Id", headers);
                msg['Reply-To'] = getHeaderVal("From",headers);
                msg['In-Reply-To'] = getHeaderVal('In-Reply-To', headers) || msg['Message-Id'];
                msg['References'] = getHeaderVal('References', headers) || msg['Message-Id'];
            break;
            case 'forward': // Fwd:
                attaches = getAttchList(message);
                subject = parseSubject(getHeaderVal('Subject', headers),'Fwd');
                action = 'Forward';
            break;
        }
    }

    var oFReader = new FileReader(), file = '', files = '', cur_index = 0;
    oFReader.onload = function(oFREvent) {
        file = files[cur_index];
        vm.get('attaches').push({
            filename: file.name,
            result: oFREvent.target.result.split('base64,')[1],
            type: file.rawFile.type,
            size: file.size
        });
        cur_index++;
        if(cur_index == files.length){
            files = 0;
            if (readySend) {
                gmailControler.send(vm);
                readySend = false;
            }
        }else{
            oFReader.readAsDataURL(files[cur_index].rawFile);
        }
    };

    var authResult = Workport.Google.getAuthResult();
    var vm = kendo.observable($.extend({
        headers:headers,
        subject:subject,
        to: to,
        cc: cc,
        bcc: bcc,
        from: From,
        content: content,
        filename: '',
        attaches: attaches,
        inline:[],
        contacts:gmailControler.GoogleContacts(),
        att_size: function() {
            var attaches = this.get('attaches'),
                size = 0;
            for (var i = 0, l = attaches.length; i < l; i++) {
                size += attaches[i].size;
            }
            return parseInt(size / 1024 / 1024) + 'MB';
        },
        action: action,
        onSend: function(e) {
            if (files) {
                Workport.utils.alertMsg('Confirmation alert', "The browsed content is not attached to the post. Click 'Yes' to send with attachment or 'No' to send without attachment", [{
                    name: 'Yes',
                    class: 'btn yes',
                    css: {},
                    action: function(e) {
                        oFReader.readAsDataURL(files[0].rawFile);
                        cur_index = 0;
                        vm.set('enableAttach', false);
                        vm.set('filename', '');
                        document.getElementById('gmail_file_form').reset();
                        readySend = true;
                    }
                }, {
                    name: 'No',
                    class: 'btn no',
                    css: {},
                    action: function(e) {
                        gmailControler.send(vm);
                    }
                }]);
            } else
                gmailControler.send(vm);
        },
        onSaveToDrafts:function(){
            gmailControler.saveInDrafts(vm.toJSON());
        },
        onCancel: function() {
            gmailControler.showFirstMail();
        },
        onFileChange: function(e) {
            files = e.files;
            var attaches = this.get('attaches'), size = 0, file_names = [];
            if (files.length == 0) {
                return;
            }
            for(var i = 0, l = files.length; i < l; i++){
                file_names.push(files[i].name);
            }
            this.set('filename', file_names.join(', '));
            for(var i = 0, l = files.length; i < l; i++){
                if (files[i].size > MAX_SIZE) {
                    Workport.utils.alertMsg("Error alert", 'The file you are trying to send exceeds the 25MB attachment limit<br> But don\'t worry, you can send it using Google Drive', function(_data) {});
                    this.set('enableAttach', false);
                    return;
                }
            }
            this.set('enableAttach', true);
        },
        onAttach: function(e) {
            if(files){
                cur_index = 0;
                oFReader.readAsDataURL(files[cur_index].rawFile);
                this.set('enableAttach', false);
                this.set('filename', '');
                document.getElementById('gmail_file_form').reset();
            }
        },
        enableAttach: false,
        attachCursor:function(){ return this.get('enableAttach') ? 'pointer':'auto'; },
        onDelete: function(e) { this.get('attaches').splice($(e.target).data('att_index'), 1); }
    }, msg));
    return vm;
}

var gmailimageFReader = new FileReader(), gmail_image_file = '';
gmailimageFReader.onload = function(e) {
    console.log(e.target.result);
    var cvm = gmailControler.getComposeVM();
    var cid = Math.uuid();
    cvm.get('inline').push({
        filename: gmail_image_file.name,
        result: e.target.result.split('base64,')[1],
        type: gmail_image_file.type,
        size: gmail_image_file.size,
        cid:cid
    });
    var editor = $("#ta_gmail_compose").data("kendoEditor");
    editor.exec("inserthtml", { value: '<img src="'+ e.target.result +'" />'});
};

function onSelect(e) {
    $.each(e.files, function (index, value) {
        gmail_image_file  = value;
        gmailimageFReader.readAsDataURL(gmail_image_file);
        console.log(gmail_image_file);
    });
}

function on_img_error(target){
    var target = $(target);
    var from = target.data('from').toLocaleUpperCase();
    target.parent().html((from[0] == '"' ? from[1] : from[0]));
    target.remove();
}

$(function() {
    gmailControler.init();
});